//
//  HEIMTWFormCell.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/24.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEIMTWFormCell.h"
#import "HETWFormObject.h"
#import "KNPhotoBrowser.h"
#import <SDAnimatedImageView.h>
#import "HEIMVideoObject.h"
#import "HEGridImageView.h"
#import "HEFormGridImageView.h"

@interface HEIMTWFormCell ()<KNPhotoBrowserDelegate>
 
@property(nonatomic, strong) UILabel *symptomLb;
@property(nonatomic, strong) UILabel *diseaLb;
@property(nonatomic, strong) UILabel *durationLb;
@property(nonatomic, strong) UILabel *helpLb;
@property(nonatomic, strong) UILabel *drugsLb;
@property(nonatomic, strong) UILabel *allergyLb;
@property(nonatomic, strong) UILabel *hisLb;


@property (nonatomic,weak) KNPhotoBrowser *photoBrowser;
@property (nonatomic,strong) NSMutableArray *itemsArr;


@end

@implementation HEIMTWFormCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
   if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
       
       self.selectionStyle = UITableViewCellSelectionStyleNone;
 
       [self initUI];
//       [self makeGesture];
   }
   return self;
}

- (void)initUI {
    
     // 症状
     UILabel *symptomLb = [UILabel new];
     symptomLb.text = @"症状：";
     symptomLb.font = DYBlodFont(16);
     symptomLb.textColor = KWhiteColor;
     [self.bubbleView addSubview: symptomLb];
  
     _symptomLb = [UILabel new];
     _symptomLb.text = @"-";
     _symptomLb.font = DYFont(16);
     _symptomLb.textColor = KWhiteColor;
     _symptomLb.numberOfLines = 0;
     [self.bubbleView addSubview:_symptomLb];
     
 //    UILabel *diseaLb = [UILabel new];
 //    diseaLb.text = @"病情描述：";
 //    diseaLb.font = DYBlodFont(16);
 //    diseaLb.textColor = KWhiteColor;
 //    [self.bubbleView addSubview: diseaLb];
 //
 //    _diseaLb = [UILabel new];
 //    _diseaLb.text = @"-";
 //    _diseaLb.font = DYFont(16);
 //    _diseaLb.textColor = KWhiteColor;
 //    _diseaLb.numberOfLines = 0;
 //    [self.bubbleView addSubview:_diseaLb];
 //
 //    UILabel *durationLb = [UILabel new];
 //    durationLb.text = @"患病时长：";
 //    durationLb.font = DYBlodFont(16);
 //    durationLb.textColor = KWhiteColor;
 //    [self.bubbleView addSubview: durationLb];
 //
 //    _durationLb = [UILabel new];
 //    _durationLb.text = @"-";
 //    _durationLb.font = DYFont(16);
 //    _durationLb.textColor = KWhiteColor;
 //    _durationLb.numberOfLines = 0;
 //    [self.bubbleView addSubview:_durationLb];
 //
 //    UILabel *helpLb = [UILabel new];
 //    helpLb.text = @"希望获得的帮助：";
 //    helpLb.font = DYBlodFont(16);
 //    helpLb.textColor = KWhiteColor;
 //    [self.bubbleView addSubview: helpLb];
 //
 //    _helpLb = [UILabel new];
 //    _helpLb.text = @"-";
 //    _helpLb.font = DYFont(16);
 //    _helpLb.textColor = KWhiteColor;
 //    _helpLb.numberOfLines = 0;
 //    [self.bubbleView addSubview:_helpLb];
 //
 //    UILabel *drugsLb = [UILabel new];
 //    drugsLb.text = @"用药情况：";
 //    drugsLb.font = DYBlodFont(16);
 //    drugsLb.textColor = KWhiteColor;
 //    [self.bubbleView addSubview: drugsLb];
 //
 //    _drugsLb = [UILabel new];
 //    _drugsLb.text = @"-";
 //    _drugsLb.font = DYFont(16);
 //    _drugsLb.textColor = KWhiteColor;
 //    _drugsLb.numberOfLines = 0;
 //    [self.bubbleView addSubview:_drugsLb];
 //
 //    UILabel *allergyLb = [UILabel new];
 //    allergyLb.text = @"过敏史：";
 //    allergyLb.font = DYBlodFont(16);
 //    allergyLb.textColor = KWhiteColor;
 //    [self.bubbleView addSubview: allergyLb];
 //
 //    _allergyLb = [UILabel new];
 //    _allergyLb.text = @"-";
 //    _allergyLb.font = DYFont(16);
 //    _allergyLb.textColor = KWhiteColor;
 //    _allergyLb.numberOfLines = 0;
 //    [self.bubbleView addSubview:_allergyLb];
 //
 //    UILabel *hisLb = [UILabel new];
 //    hisLb.text = @"既往病史：";
 //    hisLb.font = DYBlodFont(16);
 //    hisLb.textColor = KWhiteColor;
 //    [self.bubbleView addSubview: hisLb];
 //
 //    _hisLb = [UILabel new];
 //    _hisLb.text = @"-";
 //    _hisLb.font = DYFont(16);
 //    _hisLb.textColor = KWhiteColor;
 //    _hisLb.numberOfLines = 0;
 //    [self.bubbleView addSubview:_hisLb];
  
     [symptomLb mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.bubbleView).mas_offset(10);
         make.left.equalTo(self.bubbleView).mas_offset(10);
     }];
     [symptomLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
     
     [_symptomLb mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.bubbleView).mas_offset(10);
         make.left.equalTo(symptomLb.mas_right);
         make.right.equalTo(self.bubbleView).mas_offset(-10);
     }];
     
 //    [diseaLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_symptomLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(self.bubbleView).mas_offset(10);
 //    }];
 //    [diseaLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
 //
 //    [_diseaLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_symptomLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(diseaLb.mas_right);
 //        make.right.equalTo(self.bubbleView).mas_offset(-10);
 //    }];
 //
 //    [durationLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_diseaLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(self.bubbleView).mas_offset(10);
 //    }];
 //    [durationLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
 //
 //    [_durationLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_diseaLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(durationLb.mas_right);
 //        make.right.equalTo(self.bubbleView).mas_offset(-10);
 //    }];
 //
 //    [helpLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_durationLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(self.bubbleView).mas_offset(10);
 //    }];
 //    [helpLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
 //
 //    [_helpLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_durationLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(helpLb.mas_right);
 //        make.right.equalTo(self.bubbleView).mas_offset(-10);
 //    }];
 //
 //    [drugsLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_helpLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(self.bubbleView).mas_offset(10);
 //    }];
 //    [drugsLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
 //
 //    [_drugsLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_helpLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(drugsLb.mas_right);
 //        make.right.equalTo(self.bubbleView).mas_offset(-10);
 //    }];
 //
 //    [allergyLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_drugsLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(self.bubbleView).mas_offset(10);
 //    }];
 //    [allergyLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
 //
 //    [_allergyLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_drugsLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(allergyLb.mas_right);
 //        make.right.equalTo(self.bubbleView).mas_offset(-10);
 //    }];
 //
 //    [hisLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_allergyLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(self.bubbleView).mas_offset(10);
 //    }];
 //    [hisLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
 //
 //    [_hisLb mas_makeConstraints:^(MASConstraintMaker *make) {
 //        make.top.equalTo(_allergyLb.mas_bottom).mas_offset(10);
 //        make.left.equalTo(hisLb.mas_right);
 //        make.right.equalTo(self.bubbleView).mas_offset(-10);
 //    }];
       
 }

 - (void)configCellWithModel:(HEIMMessageModel *)model {
     
     HETWFormObject *form = (HETWFormObject *)model.message.messageObject;
     _symptomLb.text = [self notNull:form.formContents[0].message.text];
 //    _diseaLb.text = [self notNull:form.formContents[1].message.text];
 //    _helpLb.text = [self notNull:form.formContents[2].message.text];
 //    _durationLb.text = [self notNull:form.formContents[3].message.text];
 //    _drugsLb.text = [self notNull:form.formContents[4].message.text];
 //    _allergyLb.text = [self notNull:form.formContents[5].message.text];
 //    _hisLb.text = [self notNull:form.formContents[6].message.text];

     [self.bubbleView mas_updateConstraints:^(MASConstraintMaker *make) {
         make.width.mas_offset(model.contentWidth);
     }];
     
     // 必须写
     [self refreshData:model];
     
     dispatch_main_async_safe(^{
         [self nineView];
     })
 }

 - (NSString *)notNull:(NSString *)str {
     if ([DYTools isBlankString:str]) {
         return @"-";
     }
     return str;
 }

 - (void)nineView {
     
     if (self.itemsArr.count > 0) {
         return;
     }
     
     HETWFormObject *form = (HETWFormObject *)self.model.message.messageObject;
     NSMutableArray *urlArr = @[].mutableCopy;

     NSObject *object1 = NULL;
     NSObject *object2 = NULL;

     if (form.formContents.count >= 2) {
         HEIMMessageModel *imageModel = form.formContents[1];
         
         object1 = imageModel.message.messageObject;
     }
  
     if (form.formContents.count >= 3) {
         HEIMMessageModel *videoModel = form.formContents[2];

         object2 =  videoModel.message.messageObject;
     }
     
     if ([object1 isKindOfClass:HEIMImageObject.class]) {
         HEIMImageObject *imageArr = (HEIMImageObject *)object1;
         NSArray <HEIMImageObject *> *images = imageArr.imageArray;

         for (HEIMImageObject *object in images) {
             [urlArr addObject:object];
         }
     }else {
         HEIMVideoObject *video = (HEIMVideoObject *)object1;

         for (NSString *object in video.urls) {
             HEIMVideoObject *obj = [HEIMVideoObject new];
             obj.url = [NSURL URLWithString:object];
             [urlArr addObject:obj];
         }
     }
     
     if ([object2 isKindOfClass:HEIMImageObject.class]) {
         HEIMImageObject *imageArr = (HEIMImageObject *)object2;
         NSArray <HEIMImageObject *> *images = imageArr.imageArray;

         for (HEIMImageObject *object in images) {
             [urlArr addObject:object];
         }
     }else {
         HEIMVideoObject *video = (HEIMVideoObject *)object2;

         for (NSString *object in video.urls) {
             HEIMVideoObject *obj = [HEIMVideoObject new];
             obj.url = [NSURL URLWithString:object];
             [urlArr addObject:obj];
         }
     }
     
     
 //    if (form.formContents.count >= 8) {
 //        HEIMMessageModel *imageModel = form.formContents[7];
 //
 //        HEIMImageObject *imageArr = (HEIMImageObject *)imageModel.message.messageObject;
 //        NSArray <HEIMImageObject *> *images = imageArr.imageArray;
 //
 //        for (HEIMImageObject *object in images) {
 //            [urlArr addObject:object];
 //        }
 //    }
 //
 //    if (form.formContents.count >= 9) {
 //        HEIMMessageModel *videoModel = form.formContents[8];
 //
 //        HEIMVideoObject *video = (HEIMVideoObject *)videoModel.message.messageObject;
 //
 //        for (NSString *object in video.urls) {
 //            HEIMVideoObject *obj = [HEIMVideoObject new];
 //            obj.url = [NSURL URLWithString:object];
 //            [urlArr addObject:obj];
 //        }
 //    }
     
     CGFloat viewWidth = self.model.contentWidth;

     UIView *view = [UIView new];
     [self.bubbleView addSubview:view];
     
     CGFloat wd = (viewWidth - 40) / 3 + 10;
     NSInteger a = urlArr.count/3;
     NSInteger b = (urlArr.count%3) > 0 ? 1 : 0;

     NSInteger row = a + b;
     CGFloat ht = row * wd;
  
     [view mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(_symptomLb.mas_bottom).mas_offset(10);
         make.left.equalTo(self.bubbleView).mas_offset(0);
         make.right.equalTo(self.bubbleView).mas_offset(-0);
         make.height.mas_offset(ht);
         make.bottom.equalTo(self.bubbleView).mas_offset(-10);
     }];
     
     [self layoutIfNeeded];
     
     for (NSInteger i = 0 ;i < urlArr.count; i ++) {
         NSObject *obj = urlArr[i];

         UIImageView *imageView = [[UIImageView alloc] init];
         imageView.contentMode = UIViewContentModeScaleAspectFill;
         imageView.clipsToBounds = YES;
         imageView.userInteractionEnabled = YES;
         [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDidClick:)]];
         imageView.tag = i + 1;
         
         imageView.backgroundColor = [UIColor grayColor];
         CGFloat width = (view.frame.size.width - 40) / 3;
         NSInteger row = i / 3;
         NSInteger col = i % 3;
         CGFloat x = 10 + col * (10 + width);
         CGFloat y = 10 + row * (10 + width);
         imageView.frame = CGRectMake(x, y, width, width);
         
         KNPhotoItems *items = [[KNPhotoItems alloc] init];
         items.sourceView = imageView;
         
         
         if ([obj isKindOfClass:HEIMVideoObject.class]) {
              
             UIButton *_playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
             _playBtn.userInteractionEnabled = NO;
             [_playBtn setImage:[UIImage imageNamed:@"new_allPlay_44x44_"] forState:UIControlStateNormal];
             [imageView addSubview:_playBtn];
             
             [_playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                 make.centerX.centerY.equalTo(imageView);
                 make.width.height.offset(width * 0.4);
             }];
             
             HEIMVideoObject *videoObj = (HEIMVideoObject *)obj;
             
             AVURLAsset *avAsset = [AVURLAsset assetWithURL: videoObj.url];

 //            if ([videoObj.url hasPrefix:@"http"]) {
             if (avAsset) {
                 CGFloat padding = 5, imageViewLength = ([UIScreen mainScreen].bounds.size.width - padding * 2) / 3 - 10, scale = [UIScreen mainScreen].scale;
                 CGSize imageViewSize = CGSizeMake(imageViewLength * scale, imageViewLength * scale);
                 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                     AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:avAsset];
                     generator.appliesPreferredTrackTransform = YES;
                     generator.maximumSize = imageViewSize;
                     NSError *error = nil;
                     CGImageRef cgImage = [generator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:NULL error:&error];
                     dispatch_async(dispatch_get_main_queue(), ^{
                         imageView.image = [UIImage imageWithCGImage:cgImage];
                     });
                 });
             }
             
             items.isVideo = true;
             items.url = videoObj.url.absoluteString;
             
         }else {
             HEIMImageObject *imgObj = (HEIMImageObject *)obj;
             [imageView sd_setImageWithURL:imgObj.url placeholderImage:nil];
             
             items.url = [imgObj.url.absoluteString stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
         }
               
         
         [self.itemsArr addObject:items];
         
         [view addSubview:imageView];
     }
 }

 - (NSMutableArray *)itemsArr{
     if (!_itemsArr) {
         _itemsArr = [NSMutableArray array];
     }
     return _itemsArr;
 }

 - (void)imageViewDidClick:(UITapGestureRecognizer *)tap{
     KNPhotoBrowser *photoBrowser = [[KNPhotoBrowser alloc] init];
     photoBrowser.itemsArr = [self.itemsArr copy];
 //    photoBrowser.isNeedPageControl = true; // if it has video to play , I do not suggest you to use PageControl
     photoBrowser.isNeedPageNumView = true;
     photoBrowser.isNeedRightTopBtn = true;
     photoBrowser.isNeedPictureLongPress = true;
     photoBrowser.isNeedPanGesture = true;
     photoBrowser.isNeedPrefetch = true;
     photoBrowser.isNeedAutoPlay = true;
     
     photoBrowser.currentIndex = tap.view.tag - 1;
     photoBrowser.delegate = self;
     [photoBrowser present];
     
     _photoBrowser = photoBrowser;
 }
  
 #pragma mark - delegate

 /* photoBrowser 右上角按钮的点击 */
 - (void)photoBrowserRightOperationAction{
     
     __weak typeof(self) weakself = self;
     KNActionSheet *actionSheet = [[KNActionSheet share] initWithTitle:@"" cancelTitle:@"" titleArray:@[@"保存"].mutableCopy destructiveArray:@[@"0"].mutableCopy actionSheetBlock:^(NSInteger buttonIndex) {
         if (buttonIndex == 0) {
  
             [weakself toSaveImage:[NSURL URLWithString:weakself.photoBrowser.itemsArr[weakself.photoBrowser.currentIndex].url]];
         }
     }];
     
     [actionSheet show];
 }

 /// long press
 /// @param photoBrowser pb
 /// @param longPress press
 - (void)photoBrowser:(KNPhotoBrowser *)photoBrowser longPress:(UILongPressGestureRecognizer *)longPress {
     if (longPress.state == UIGestureRecognizerStateBegan) {
         [photoBrowser setImmediatelyPlayerRate:2];
     }else if (longPress.state == UIGestureRecognizerStateEnded || longPress.state == UIGestureRecognizerStateCancelled || longPress.state == UIGestureRecognizerStateFailed || longPress.state == UIGestureRecognizerStateRecognized){
         [photoBrowser setImmediatelyPlayerRate:1];
     }
 }


 - (void)toSaveImage:(NSURL *)url {
     SDWebImageManager *manager = [SDWebImageManager sharedManager];
     if ([manager cacheKeyForURL:url]) {
        [[manager imageCache] queryImageForKey:url.absoluteString options:SDWebImageFromCacheOnly context:nil completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
            // 保存图片到相册中
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
         }];
         return;
     }
     else {
         //从网络下载图片
         NSData *data = [NSData dataWithContentsOfURL:url];
         UIImage *img = [UIImage imageWithData:data];
         // 保存图片到相册中
         UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
     }
 }

 //保存图片完成之后的回调
 - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
   contextInfo:(void *)contextInfo {
     if (error != NULL) {
         [Dialog toast:@"图片保存失败" delay:2.0];
     }
     else  // No errors
     {
         [Dialog toast:@"图片保存成功" delay:2.0];
     }
 }



 @end
